<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./colorpicker.js"></script>
</head>
<style>
    *{ margin:0;padding:0;}
    .picker{
        width: 48px;
        height: 20px;
        display: inline-block;
        margin-top: 5px;
    }
</style>
<body>
    <div style=" height: 30px;display: inline-block;line-height: 30px;">颜色：<div class="picker" id="colorPicker"></div></div>
    <span style="margin-left: 30px;">请选择线条粗细（像素）：</span>
    <select id="linewidth" onchange="setLine()">
        <option value="1">1px</option>
        <option value="2">2px</option>
        <option value="3">3px</option>
        <option value="4">4px</option>
        <option value="5">5px</option>
    </select>
    <input type="button"  id="clear" value="清除图像">
    <canvas id="drawcanvas" width="800px" height="500px" style="border: 2px solid #333333;display: block;margin-top: 10px;"></canvas>
</body>
</html>
    <script>
        let clear = document.querySelector("#clear");
        let draw = document.querySelector("#drawcanvas");
        let drawP = draw.getContext("2d");
        let linew = document.querySelector("#linewidth")
        clear.addEventListener("click",function(){
            drawP.clearRect(0,0,800,500);
            console.log("已清除");
        })
        Colorpicker.create({
	        el: "colorPicker", //元素id
	        color: "#000fff", //默认颜色
	        change: function (elem, hex) {
		        //选中颜色发生改变时事件
		    elem.style.backgroundColor = hex;
            drawP.strokeStyle = hex;
            console.log("画笔颜色已更改")
	                }
        });
        //粗细选择
        function setLine(){
            var wid = linew.options[linew.selectedIndex].value;
            if(wid == 1){
                drawP.lineWidth = 1;
                console.log("画笔粗细为1px")
            }
            if(wid == 2){
                drawP.lineWidth = 2;
                console.log("画笔粗细为2px")
            }
            if(wid == 3){
                drawP.lineWidth = 3;
                console.log("画笔粗细为3px")
            }
            if(wid == 4){
                drawP.lineWidth = 4;
                console.log("画笔粗细为4px")
            }
            if(wid == 5){
                drawP.lineWidth = 5;
                console.log("画笔粗细为5px")
            }
        };

        let offleft = draw.offsetLeft;
        let offtop = draw.offsetTop;
        draw.addEventListener("mousedown",function(e){

            drawP.moveTo(e.clientX-offleft,e.clientY-offtop);//获取起始点
            draw.onmousemove = function(e){
                drawP.lineTo(e.clientX-offleft,e.clientY-offtop);
                drawP.stroke();
            }
            draw.onmouseup = function(){
                draw.onmousemove = null;
                drawP.beginPath();
            }
        });
        
    </script>